package com.dgut.lotterySystem.common.utils;

// 自己完成一个Jackson字符串的生成和转化

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;


import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {

    private JacksonUtil(){}

    /**
     * 单例创建ObjectMapper
     */
    private final static ObjectMapper OBJECT_MAPPER;

    static{
        OBJECT_MAPPER=new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }
    //再次进行封装，方便调用
    protected static <T> T tryParse(Callable<T> parser){
        return tryParse(parser, JacksonException.class);
    }

    //catch异常
    //直接拿 package org.springframework.boot.json;
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
                throw new IllegalStateException(var4);
        }
    }

    /**
     * 序列化方法
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(()->{
          return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }

    /**
     * 反序列化Object的方法
     * @param content
     * @param contentType
     * @return
     * @param <T>
     */
   public static <T> T readValue(String content,Class<T> contentType){
        return JacksonUtil.tryParse(()->{
           return JacksonUtil.getObjectMapper().readValue(content,contentType);
        });
   }


   public static <T> T readListValue(String content,Class<?> paramClasses){
       JavaType javaType=JacksonUtil.getObjectMapper().getTypeFactory()
                         .constructParametricType(List.class,paramClasses);
       return JacksonUtil.tryParse(()->{
          return JacksonUtil.getObjectMapper().readValue(content,javaType);
       });
   }



}
